package com.lhh.springcloud.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author 李洪豪
 * @Sno 20220301044
 */
@Configuration
public class DataSourceProxyConfig {
    @Value("${mybatis.mapper-locations}")
    private  String mapperLocations;

    //配置druid数据源
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DruidDataSource druidDataSource(){
        return new DruidDataSource();
    }

    //配置seata代理druid数据源
    @Bean
    public DataSourceProxy dataSourceProxy(DruidDataSource druidDataSource){
        return new DataSourceProxy(druidDataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceProxy);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources
                (mapperLocations));
        //解析该路径并获取所有匹配的资源文件。
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        //设置事务管理策略为 Spring 管理的事务。
        // SpringManagedTransactionFactory是 yBatis提供的与Spring事务管理集成的事务工厂类，确保 MyBatis 使用 Spring 的事务上下文
        return sqlSessionFactoryBean.getObject();
    }
}
